package chagine.core.lock;


import chagine.core.current.CurrentTenant;
import chagine.core.current.CurrentUser;
import chagine.core.lock.redis.RedisReentrantLock;
import chagine.core.lock.redis.util.SeeingLockRedisUtil;
import chagine.core.lock.redis.util.SeeingLockRedisUtilFactory;

/**
 * 浙江贯通技术股份有限公司
 *
 * @author 张正伟
 * @create 2019-07-02 10:35
 */
public class SeeingLockFactory {

    private SeeingLockRedisUtilFactory seeingLockRedisUtilFactory;

    public SeeingLockFactory(SeeingLockRedisUtilFactory seeingLockRedisUtilFactory) {
        this.seeingLockRedisUtilFactory = seeingLockRedisUtilFactory;
    }

    /**
     * 创建一个平台级的锁，支持reids 数据库的自定义
     *
     * @param lockKey    锁用的KEY
     * @param lockExpire 锁超时时间，单位millis
     * @param dbIndex    reids 数据库
     */
    public RedisReentrantLock systemLock(String lockKey, long lockExpire, int dbIndex) {
        SeeingLockRedisUtil lockRedisUtil = seeingLockRedisUtilFactory.getSeeingLockRedisUtil(dbIndex);
        return new RedisReentrantLock(lockKey, lockExpire, lockRedisUtil);
    }

    public RedisReentrantLock systemLock(String lockKey, long lockExpire) {
        return systemLock(lockKey, lockExpire, -1);
    }

    public RedisReentrantLock systemLock(String lockKey) {
        return systemLock(lockKey, -1, -1);
    }

    /**
     * 创建一个租户级的锁,支持Redis数据库的自定义
     *
     * @param lockKey    锁用的KEY
     * @param lockExpire 锁超时时间，单位millis
     * @param dbIndex    redis数据库定义
     */
    public RedisReentrantLock tenantLock(String lockKey, long lockExpire, int dbIndex) {
        SeeingLockRedisUtil lockRedisUtil = seeingLockRedisUtilFactory.getSeeingLockRedisUtil(dbIndex);
        return new RedisReentrantLock(CurrentTenant.currentTenant() + "_" + lockKey, lockExpire, lockRedisUtil);
    }

    public RedisReentrantLock tenantLock(String lockKey, long lockExpire) {
        return tenantLock(lockKey, lockExpire, -1);
    }

    public RedisReentrantLock tenantLock(String lockKey) {
        return tenantLock(lockKey, -1, -1);
    }

    /**
     * 创建一个租户级的锁
     *
     * @param lockKey    锁用的KEY
     * @param lockExpire 锁超时时间，单位millis
     * @param dbIndex    redis数据DB
     */
    public RedisReentrantLock userLock(String lockKey, long lockExpire, int dbIndex) {
        SeeingLockRedisUtil lockRedisUtil = seeingLockRedisUtilFactory.getSeeingLockRedisUtil(dbIndex);
        return new RedisReentrantLock(CurrentTenant.currentTenant() + "_" + CurrentUser.currentUser() + "_" + lockKey,
                lockExpire,
                lockRedisUtil);
    }

    public RedisReentrantLock userLock(String lockKey, long lockExpire) {
        return userLock(lockKey, lockExpire, -1);
    }

    public RedisReentrantLock userLock(String lockKey) {
        return userLock(lockKey, -1, -1);
    }
}
